class UserInvitationObserver < ActiveRecord::Observer
  
  def after_create(user_invitation)
    update_points(user_invitation)  
  end
  
  
  private 
  def update_points(user_invitation)
    conditions = nil
    if user_invitation.invited_user_email
      conditions =   ["user_id=:user_id and invited_user_email=:invited_user_email and id<>:id", {:user_id=>user_invitation.user_id,:invited_user_email=>user_invitation.invited_user_email,:id=>user_invitation.id }]
    else
      conditions = ["user_id=:user_id and invited_user_fb_uid=:invited_user_fb_uid and id<>:id", {:user_id=>user_invitation.user_id,:invited_user_fb_uid=>user_invitation.invited_user_fb_uid,:id=>user_invitation.id }]
    end
    
    #ui = UserInvitation.find(:first, :conditions=>["user_id=:user_id and invited_user_fb_uid=:invited_user_fb_uid and id<>:id", {:user_id=>user_invitation.user_id,:invited_user_fb_uid=>user_invitation.invited_user_fb_uid,:id=>user_invitation.id }])
    ui = UserInvitation.find(:first, :conditions=>conditions)
    
    if !ui 
      user = User.find(user_invitation.user_id)
      points = user.active_campaign.points_invite_friends
      user.points += points
      user.save!
      #if the user is in any campaign
      uc = user.active_user_campaign
      if uc
        uc.points +=points
        uc.save!
      end
    end
  end
  
  
  
end
